/**
 * 
 */
package net.bingosoft.common.upload;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bingosoft.common.config.Config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Form所有请求的入口Servlet，负责各种请求的处理和分发
 * @author elvis
 * changelog : yangdongyu@2008-03-19 将该类重构成只处理文件上传的Servlet
 */
public class FileUploadServlet extends HttpServlet {
    
	private static final long serialVersionUID = 1L;

	private static final Logger log = LoggerFactory.getLogger(FileUploadServlet.class);
    
    private ServletContext servletContext = null;    
    
    @SuppressWarnings("unchecked")
	public void init(ServletConfig config) throws ServletException {
        this.servletContext = config.getServletContext();        
        UploadManager.configBySpring(servletContext);
        UploadConfig uploadConfig = UploadManager.getConfig();
        Enumeration<String> e = config.getInitParameterNames();
        while(e.hasMoreElements()){
            String name  = e.nextElement();
            String value = config.getInitParameter(name);
            log.debug("found a config[{}={}],put it into the configuration properties",name,value);
            if(UploadConfig.isConfigField(name)){
                uploadConfig.config(name, value);
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	 String characterEncoding = Config.getString("CHARACTER_ENCODING", "UTF-8");
         resp.setContentType("text/html;charset=" + characterEncoding);
         req.setCharacterEncoding(characterEncoding);
         //处理文件上传
         doUpload(req, resp);
    }
    
    
    private void doUpload(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        UploadResult result = UploadManager.upload(request, response);
        String jsonResult   = result.toJSON();
        if(log.isDebugEnabled()){
            log.debug("upload result:{}",jsonResult);
        }
        response.getWriter().write(jsonResult);
        response.getWriter().flush();
    }
}
